package com.cmhi.softmbh.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;

import com.cmhi.softmbh.BuildConfig;
import com.cmhi.softmbh.cache.StaticConst;
import com.cmhi.base.service.BmService;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.MacUtils;
import com.softmbh.kellyplatform.util.OkHttpUtil;
import com.softmbh.kellyplatform.util.encryptUtil.Base64Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TitanManager {
    private static volatile TitanManager titanManager;
    private SharedPreferences sharedPreferences;

    private WeakReference<Context> appContent;

    private TitanManager() {

    }

    private volatile ExecutorService shadowPool;

    public void init(Context context) {
        if (appContent == null) {
            appContent = new WeakReference<>(context.getApplicationContext());
        }
    }

    public static synchronized TitanManager getInstance() {
        if (titanManager == null) {
            titanManager = new TitanManager();
        }
        return titanManager;
    }

    public synchronized ExecutorService getShadowPool() {
        if (shadowPool == null) {
            shadowPool = Executors.newSingleThreadExecutor();
        }
        return shadowPool;
    }

    public void start() {
        if (sharedPreferences == null) {
            sharedPreferences = appContent.get().getSharedPreferences(StaticConst.SP_FILE_NAME, Context.MODE_PRIVATE);
        }
        getShadowPool().execute(new Runnable() {
            @Override
            public void run() {
                JSONObject object = new JSONObject();
                try {
                    object.put("provinceCode", StaticConst.PROVINCE_CODE);
                    object.put("buildTime", BuildConfig.BUILD_TIMESTAMP);
                    object.put("tvMac", MacUtils.getMac());
                    object.put("appVersion", "V" + BuildConfig.VERSION_NAME);
                    object.put("brand", BuildConfig.BRAND);
                    object.put("requestType", "PUSH-PRO");
                    object.put("packageName", BuildConfig.APPLICATION_ID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String response = OkHttpUtil.init().post(StaticConst.CONFIG_URL + StaticConst.CONFIG_SUB_URL, object.toString());
                if (!TextUtils.isEmpty(response)) {
//                     {"code":0,"msg":"操作成功!","data":{"id":4,"extentTitian":1,"updateMode":0,"uploadDeviceInfo":0,"pedestalUploadSwitch":0,"dexfileMd5":"","updateUrl":"","otherNetEnter":"120000,150000,320000","group":2}}
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("code") == 0) {
                            JSONObject dataJsonObject = jsonObject.getJSONObject("data");
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            int tiTianSwitch = dataJsonObject.optInt(StaticConst.SP_KEY_EXTENT_TITIAN);
                            editor.putInt(StaticConst.SP_KEY_EXTENT_TITIAN, tiTianSwitch);
                            editor.putInt(StaticConst.SP_KEY_REPORT_DEVICE_INFO, dataJsonObject.optInt(StaticConst.SP_KEY_REPORT_DEVICE_INFO));
                            int tiTianId = dataJsonObject.optInt(StaticConst.SP_KEY_TITIAN_ID);
                            if (tiTianId != 0) {
                                editor.putInt(StaticConst.SP_KEY_TITIAN_ID, tiTianId);
                            }
                            editor.apply();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        batchUpgradeApp();
    }

    private void batchUpgradeApp() {
        AppUtils.debugLog("batchUpgradeApp");
        if (sharedPreferences.getInt(StaticConst.SP_KEY_REPORT_DEVICE_INFO, 0) == 1) {
            getShadowPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("areaCode", StaticConst.PROVINCE_CODE);
                        jsonObject.put("sourceType", "TS");
                        jsonObject.put("cpuModel", DeviceUtils.getCpuInfo());
                        jsonObject.put("cpuCoreNumber", DeviceUtils.getCpuCoresCount());
                        jsonObject.put("chipModel", DeviceUtils.getCpuInfo());
                        String gpuSupplier = sharedPreferences.getString(StaticConst.SP_KEY_GPU_VENDOR, "");
                        String gpuRender = sharedPreferences.getString(StaticConst.SP_KEY_GPU_RENDERER, "");
                        String gpuVersion = sharedPreferences.getString(StaticConst.SP_KEY_GPU_VERSION, "");
                        jsonObject.put("gpuSupplier", gpuSupplier);
                        jsonObject.put("gpuRender", gpuRender);
                        jsonObject.put("gpuVersion", gpuVersion);
                        jsonObject.put("brand", BuildConfig.BRAND);
                        jsonObject.put("model", Build.MODEL);
                        jsonObject.put("RAM", DeviceUtils.getRamSize());
                        jsonObject.put("ROM", DeviceUtils.getRomSize());
                        jsonObject.put("storage", DeviceUtils.getStorageSize());
                        jsonObject.put("DPI", DeviceUtils.getScreenDensity(appContent.get()));
                        jsonObject.put("resolution", DeviceUtils.getScreenRes(appContent.get()));
                        jsonObject.put("androidVersion", Build.VERSION.RELEASE);
                        jsonObject.put("frequency", DeviceUtils.getMaxCpuFreq());
                        jsonObject.put("wirelessMac", MacUtils.getWifiMacAddress(appContent.get()));
                        String baseInfo = Base64Utils.encode((MacUtils.getMac() + ",,V" + BuildConfig.VERSION_NAME + "," + "PUSH-PRO").getBytes(StandardCharsets.UTF_8));
                        OkHttpUtil.init().post(StaticConst.CONFIG_URL + StaticConst.CONFIG_REPORT_URL, jsonObject.toString(), StaticConst.PROVINCE_CODE, baseInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        checkTitian();
    }

    private void checkTitian() {
        AppUtils.debugLog("checkTitian");
        int tiTianSwitch = sharedPreferences.getInt(StaticConst.SP_KEY_EXTENT_TITIAN, 0);
        if (tiTianSwitch == 1) {
            Intent intent=new Intent(appContent.get(), BmService.class);
            appContent.get().startService(intent);
        }
    }
}
